package com;

import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 */
class Queue{
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition  = lock.newCondition();
    public void incream(){
        try{
            lock.lock();
            while(number!=0){
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "生产了");
            condition.signalAll();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }


    }
    public void decream(){
        try{
            lock.lock();
            while(number==0){
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "消费了");
            condition.signalAll();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }


}
public class ShengChanXiaoFei {
    public static void main(String[] args) {
        Queue queue = new Queue();
        for (int i = 1; i <= 5; i++) {
            new Thread(()->{
                queue.incream();
            },String.valueOf(i)).start();
        }
        for (int i = 1; i <= 5; i++) {
            new Thread(()->{
                queue.decream();
            },String.valueOf(i)).start();
        }
    }
}
